//#include <string.h>
#include "parser.h"
//#include "auxiliary.h"

#include <linux/module.h>
#include <linux/ctype.h>

#include "regexp.c"

// if you change it, change in parseArgs.c and server/Commands.java as well
#define MAX_PATTERN_LEN 250

//#define malloc(s) kmalloc((s), GFP_KERNEL)

static int hex2dec(char c)
{
        if (c >= '0' && c <= '9') return c - '0';
        if (c >= 'a' && c <= 'f') return c - 'a' + 10;
        if (c >= 'A' && c <= 'F') return c - 'A' + 10;
        // TODO: log("hex2dec: bad value!\n");
        return 1;
}

/* takes a string with \xHH escapes and returns one with the characters
they stand for */
static char * pre_process(char * s)
{
        char * result = malloc(strlen(s) + 1);
        int sindex = 0, rindex = 0;
        while( sindex < strlen(s) )  
        {
            if( sindex + 3 < strlen(s) &&
                s[sindex] == '\\' && s[sindex+1] == 'x' &&
                isxdigit(s[sindex + 2]) && isxdigit(s[sindex + 3]) )
                {
                        /* carefully remember to call tolower here... */
                        result[rindex] = tolower( hex2dec(s[sindex + 2])*16 +
                                                  hex2dec(s[sindex + 3] ) );
                        sindex += 3; /* 4 total */
                }
                else 
                        result[rindex] = tolower(s[sindex]);

                sindex++;  
                rindex++;
        }
        result[rindex] = '\0';

        return result;
}

regexp* reg_compile(char* re)
{
   int patternlen;
   
   patternlen = strlen(re);

   if(patternlen > MAX_PATTERN_LEN){
		        // TODO: log("Pattern is too long!  Max is %d.\n", MAX_PATTERN_LEN);
		return NULL;
	}

   re = pre_process(re); /* do \xHH escapes */
   return regcomp(re, &patternlen);
}

int parser(regexp* pattern, char* input, int inputlen)
{
   int c;

   for(c = 0; c < inputlen; c++)	
      input[c] = tolower(input[c]);
   return regexec(pattern, input);
}
